package com.jyskkebank.android.toggl;

import java.io.IOException;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.SpannableStringBuilder;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.MenuItem.OnMenuItemClickListener;
import android.view.View;
import android.view.View.OnKeyListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.jyskebank.android.toggl.domain.Login;
import com.jyskkebank.android.util.Utility;

public class LoginActivity extends Activity implements View.OnClickListener {
	/** Called when the activity is first created. */
	Context mContext;
	String userName = null;
	String password = null;
	boolean checkboxClicked;
	public static final String PREFS_NAME = "MyPrefsFile";
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.menu, menu);
		return true;
	}

	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.about:
			item.setOnMenuItemClickListener(new OnMenuItemClickListener() {

				public boolean onMenuItemClick(MenuItem item) {
					onDestroy(R.id.jbtoggl);
					setContentView(R.layout.about);
					TextView aboutTextView = (TextView) findViewById(R.id.aboutText);
					aboutTextView
							.setText("JBToggl is a time tracking software that will track your time anywhere on anything: Mac, PC, iPhone, iPad, iPod, or Android. This software is created by i-bank team of Jyske Bank and the contributors are Amanpreet , Anshita , Neeraj , Pankaj, Sangeeta ");
					return false;
				}
			});
			return true;
		}
		return false;
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		Button loginBtn = (Button) findViewById(R.id.loginBtnId);
		CheckBox checkBox = (CheckBox) findViewById(R.id.remPwdId); 
		loginBtn.setOnClickListener(this);
		checkBox.setOnKeyListener(new OnKeyListener() {
			public boolean onKey(View v, int keyCode, KeyEvent event) {
				// If the event is a key-down event on the "enter" button
				if ((event.getAction() == KeyEvent.ACTION_DOWN)
						&& (keyCode == KeyEvent.KEYCODE_ENTER)) {
					onClick(v);
					return true;
				}
				return false;
			}
		});
		
		SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
		boolean checkBoxPrf = settings.getBoolean("checkBoxClicked", false);
		if(checkBoxPrf){
			CheckBox checkBoxUserPw = (CheckBox) findViewById(R.id.remPwdId);
			checkBoxUserPw.setChecked(checkBoxPrf);
			String storedUser = settings.getString("user", "");
			String storedPassword = settings.getString("password", "");
			if(!storedUser.equals("")){
				EditText userTextView=(EditText)findViewById(R.id.editNameTxtId);      
				userTextView.setText(storedUser); 
			}
			if(!storedPassword.equals("")){
				EditText pwTextView=(EditText)findViewById(R.id.editPwdTxtId);      
				pwTextView.setText(storedPassword);
			}
		}
	}

	// Implement the OnClickListener callback
	public void onClick(View v) {
		displayTask();
	}

	private void displayTask() {
		/*ProgressDialog pd = ProgressDialog.show(LoginActivity.this, "", "Loading. Please wait...", true);*/
		
		String userName = getTextValue(R.id.editNameTxtId);
		String password = getTextValue(R.id.editPwdTxtId);
		CheckBox checkBox = (CheckBox) findViewById(R.id.remPwdId);
		this.userName = userName;
		this.password = password;
		this.checkboxClicked = checkBox.isChecked();
		if (Utility.validateBeforeLogin(userName, password)) {
			goToTaskPage(userName, password);
		}
	}

	private String getTextValue(int editNameTxtId) {
		TextView txtView = (TextView) findViewById(editNameTxtId);
		String userName = ((SpannableStringBuilder) txtView.getText())
				.toString();
		return userName;
	}

	private void goToTaskPage(String userName, String password) {
		Login loginData = new Login();
		TogglService togglService = new TogglService();
		try {
			loginData = togglService.getLoginData(userName, password);
			System.out.println(loginData);
		} catch (IOException e) {
			e.printStackTrace();
		}
		onDestroy(R.id.jbtoggl);
		this.setContentView(R.layout.tasklist);
		Intent intent = new Intent(this , TaskListActivity.class);
		intent.putExtra("apiToken", loginData.getApiToken());
		System.out.println("workspaceId in LoginActivity :" + loginData.getDefaultWorkspaceId());
		intent.putExtra("workspaceId", String.valueOf(loginData.getDefaultWorkspaceId()));
		startActivity(intent);
	}

	private void onDestroy(int id) {
		super.onDestroy();
		unbindDrawables(findViewById(id));
		RelativeLayout layout = (RelativeLayout) findViewById(id);
		layout.setBackgroundDrawable(null);
		System.gc();
	}

	private void unbindDrawables(View view) {
		if (view.getBackground() != null) {
			view.getBackground().setCallback(null);
		}
		if (view instanceof ViewGroup) {
			for (int i = 0; i < ((ViewGroup) view).getChildCount(); i++) {
				unbindDrawables(((ViewGroup) view).getChildAt(i));
			}
			((ViewGroup) view).removeAllViews();
		}
	}
	
	 @Override    
	 protected void onStop(){       
		 super.onStop();      
		 SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);      
		 SharedPreferences.Editor editor = settings.edit();
		 editor.putString("user", userName);
		 editor.putString("password", password);
		 editor.putBoolean("checkBoxClicked", checkboxClicked);
		 editor.commit();    
	}
}